package beautiful.butterfly.server.httpserver.handlers.notchange;

import beautiful.butterfly.server.httpserver.handlers.HttpConst;
import beautiful.butterfly.server.httpserver.mvc.SessionContent;
import beautiful.butterfly.server.httpserver.mvc.core.ActionContext;
import beautiful.butterfly.server.httpserver.mvc.http.HttpSession;
import beautiful.butterfly.server.httpserver.mvc.http.Request;
import beautiful.butterfly.server.httpserver.mvc.http.Response;
import beautiful.butterfly.server.httpserver.mvc.http.Session;
import io.netty.handler.codec.http.Cookie;
import io.netty.handler.codec.http.DefaultCookie;
import lombok.extern.slf4j.Slf4j;

import java.util.UUID;

@Slf4j
public class SessionHandler {


    private final SessionContent sessionContent;

    private final String sessionKey;
    private final long timeout;

    public SessionHandler(SessionContent sessionContent) {

        this.sessionContent = sessionContent;

        this.sessionKey = HttpConst.DEFAULT_SESSION_KEY;
        this.timeout = 1800l;

    }

    //单纯创建session
    public Session getOrNewSession(Request request) {
        Session session = getSession(request);
        if (null == session) {
            Response response = ActionContext.getResponse();
            session = createSession(request, response);
        }
        return session;
    }

    private Session createSession(Request request, Response response) {

        long now = System.currentTimeMillis() / 1000;
        long expired = now + timeout;

        String sessionId = UUID.randomUUID().toString().replace("-", "");
        Cookie cookie = new DefaultCookie(sessionKey, sessionId);

        cookie.setHttpOnly(true);
        cookie.setSecure(false);

        Session session = new HttpSession();
        session.setId(sessionId);
        session.setCreateTime(now);
        session.setExpireTime(expired);
        sessionContent.addSession(session);

        request.setCookie(cookie);
        response.addCookie(cookie);
        return session;
    }

    private void removeSession(Session session) {
        session.getAttributeMap().clear();
        sessionContent.remove(session);

    }

    private Session getSession(Request Request) {
        String sessionId = Request.setCookie(sessionKey);
        if (sessionId == null) {
            return null;
        }
        return sessionContent.getSession(sessionId);
    }

}
